<template>
  <div class="record-popup-tree">
    <el-tree class="filter-tree" :data="treeData" :props="defaultProps" default-expand-all ref="tree" :render-content="renderContent">
    </el-tree>
  </div>
</template>

<script>
 import { mapState } from "vuex";
  export default {
    name: 'edit-tree',
    data() {
      return {
        defaultProps: {
          children: "childFolders",
          label: "label"
        },
        isEdit:false,
        editName:'',
        selectId:null,
        selectLevel:null,
        list:[]
      };
    },
    props: {
      treeData: {
        type: Array,
        default:()=>[]
      }
    },
    computed: {},

    watch: {

    },
    methods: {
      closeEdit(){
        this.isEdit=false;
      },
      append(node,data,e) {
        e = event || window.event;
        e.stopPropagation();
        console.log('新增啊啊啊');
        console.log(data);
        if (this.isEdit) {
          this.$vs.notify({
            text: "有正在编辑或添加的选项未完成！",
            color: "danger"
          });

          return false;
        }
        this.selectId='newId';
        this.selectLevel=data.level+1;
        this.editName='';
        const _child={
            ownId:data.ownId,
            pid:data.level===1?'-1':data.id,
            id:'newId',
            label: "新增节点",
            level: data.level+1,
            icon: 'el-icon-document',
            childFolders:[]
        };
        this.isEdit = true;
        // if(!data['childFolders']){
        //   this.$set(data,childFolders,[]);
        // }
        data['childFolders'].unshift(_child);
      },
      remove(node, data,e) {
        e = event || window.event;
        e.stopPropagation();
        if (this.isEdit) {
          // this.$message({
          //   message: '有正在编辑或添加的选项未完成！',
          //   type: 'error',
          //    customClass:'messageZindex'
          // });
          this.$vs.notify({
            text: "有正在编辑或添加的选项未完成！",
            color: "danger"
          });
          return false;
        }
       this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           //调删除接口
         console.log(data);
          let _ids=[data.id];
          this.$api.file.deleteFolder({data:_ids}).then(response=>{
            this.$vs.notify({
              text: "删除成功",
              color: "success"
            });
            this.$emit("query");
          });

        }).catch(() => {
          this.$vs.notify({
            text: "已取消删除",
            color: "danger"
          });
        });
      },
      update(node, data, e) {
        e = event || window.event;
        e.stopPropagation();
        if (this.isEdit) {
          this.$vs.notify({
            text: "有正在编辑或添加的选项未完成！",
            color: "danger"
          });
          return false;
        }
        this.selectId = data.id;
        this.selectLevel = data.level;
        this.editName = data.label;
        this.isEdit = true;
      },
      setEditContent(h,data,node){
        const self=this;
        return(
          <span class="treeBtns">
            <el-button
              size="mini"
              type="text"
              on-click={ () => self.cancelEdit(data, node) }
            >
              取消
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={ () => self.sureEdit(data, node) }
            >
              确认
            </el-button>
           </span>
        )
      },
      setDefaultContent(h,data,node){
        const self=this;
        return (
          <div class="treeBtns">
            <el-button
              class="el-icon-plus"
              style="color: #327bdc !important;"
              type="text"
              size="mini"
              on-click={()=>self.append(node,data)}>
            </el-button>
            {
              data.level != 1 ?
              <div style="display:inline-block;margin-left:10px;">
                <el-button
                  class="el-icon-delete"
                  style="color: red !important;"
                  type="text"
                  size="mini"
                  on-click={()=>self.remove(node,data)}>
                </el-button>
                <el-button
                  class="el-icon-edit"
                  style="color: #bec4d0 !important;"
                  type="text"
                  size="mini"
                  on-click={()=>self.update(node,data)}>
                </el-button>
              </div>
              : null
            }
          </div>
        )
      },
      renderContent(h, { node, data }) {
        // console.log(h);
         //console.log(node);
         //console.log(data);
         //console.log(this.isEdit,this.isSelect(data));
        return (
          <span class="record-tree-node">
            {
              (this.isEdit && this.isSelect(data))
                ? <input
                  placeholder="请输入..."
                  class="record-tree-editInput"
                  on-keyup={() => this.handleChangeName()}
                  value={this.editName} />
                : <span class="record-tree-nodeLabel">
                <i class={((data['childFolders']&&data['childFolders'].length>0)||data.level===1)?'el-icon-folder':'el-icon-document'}>
                </i>&nbsp;&nbsp;{data.label}</span>
            }
            {
               (this.isEdit && this.isSelect(data))
                ? this.setEditContent(h, data, node)
                : this.setDefaultContent(h, data, node)
            }
          </span>)
      },
      isSelect(data) {
       // console.log('是否选择');
        //console.log(data.id === this.selectId );
        //console.log(data.level === this.selectLevel);
        return data.id === this.selectId &&
          data.level === this.selectLevel
      },
      handleChangeName(e){
        e = event || window.event;
        e.stopPropagation();
        this.editName = e.target.value;
      },
      cancelEdit(data,node,e){
        e = event || window.event;
        e.stopPropagation();
        if (data.id==='newId') {//新增的要删除假节点
          node.parent.data.childFolders.forEach((item, i) => {
            if (item.id==='newId') {
              node.parent.data.childFolders.splice(i, 1);
            }
          })
        }
        this.selectId = null;
        this.selectLevel = null;
        this.editName = data.name;
        this.isEdit = false;
      },
      sureEdit(data,node,e){
        e = event || window.event;
        e.stopPropagation();
        if(this.editName.replace(/^\s+|\s+$/g, '')){
          if(data.id==='newId'){
           //调新增
           this.$api.file.addNewFolder({
             ownId:data.ownId,
             pid:data.pid,
             name:this.editName
           }).then(response => {
              console.log('新增文件夹');
              console.log(response);
              //添加成功后，将返回的节点加入数据中，然后删除掉id为newId的假节点
              if(response.data.code===200){
                // node.parent.data.childFolders.push({
                //     pid:data.id,
                //     ownId:data.ownId,
                //     id:response.data.data.id,
                //     label: this.editName,
                //     level: data.level+1,
                //     icon: 'el-icon-document',
                //     childFolders:[]
                // });
                // node.parent.data.childFolders.forEach((item, i) => {
                //   if (item.id==='newId') {
                //     node.parent.data.childFolders.splice(i, 1);
                //   }
                // });

                //调父 刷新树
                this.$emit("query");
                this.$vs.notify({
                  text: "新增成功!",
                  color: "success"
                });
                this.isEdit = false;
                this.selectId = null;
                this.selectLevel = null;
                console.log('新增成功',this.isEdit);
              }
           });
          }else{
            const _params={
              id:data.id,
              name:this.editName
            };
            if(data.label===this.editName){//一样的话 接口报错 前端直接return
                this.isEdit = false;
                this.selectId = null;
                this.selectLevel = null;
              return false;
            }

           this.$api.file.updateFolderName({
             id:data.id,
             name:this.editName
           }).then(response => {
              console.log('编辑文件夹');
              console.log(response);
              if(response.data.code===200){
                // node.parent.data.childFolders.forEach((item, i) => {
                //   if (item.id===data.id) {
                //    item.label=this.editName
                //   }
                // });
                 //调父 刷新树
                this.$emit("query");
                this.$vs.notify({
                  text: "编辑成功!",
                  color: "success"
                });
                this.isEdit = false;
                this.selectId = null;
                this.selectLevel = null;
                console.log('编辑成功',this.isEdit);
              }
           });
          }
        }else{
          alert('请输入文件夹名称');
        }
      },
    },

  };

</script>
<style>
  .messageZindex {
    z-index:999999 !important;
  }
   .el-message-box__wrapper{
    z-index:51003 !important;
  }

</style>
<style scoped lang="scss">


  .record {
    &-popup {
      &-tree {
        width: 100%;
        padding-left: 20px;
        height: auto;
        max-height: 500px;
        min-height: 200px;
        overflow-y: auto;
      }
    }
  }


  /deep/.el-tree-node__content{
    .treeBtns{
      display: inline-block;
      margin-left: 15px;

    }
    .record-tree-editInput{
      width: 150px;
      height: 25px;
      line-height: 25px;
      border: 1px solid #e6e6e6;
      border-radius: 3px;
      color: #666;
      text-indent: 10px;
    }
    .el-tree-node {
      margin: 3px 0;
    }
    .record-tree-nodeLabel{
      display: inline-block;
      max-width: 150px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
      vertical-align: middle;
    }
  }
</style>

